<template>
  <view class="rainfall-editor">
    <!-- 工具栏 -->
    <view class="toolbar">
      <view class="view-tabs">
        <view 
          v-for="tab in viewTabs" 
          :key="tab.value"
          class="view-tab"
          :class="{ active: currentView === tab.value }"
          @click="currentView = tab.value"
        >
          <text class="tab-icon">{{ tab.icon }}</text>
          <text class="tab-text">{{ tab.label }}</text>
        </view>
      </view>
      
      <view class="toolbar-actions" v-if="!result">
        <button class="action-btn" @click="showBatchFill = true">
          <text>📝 批量填充</text>
        </button>
        <button class="action-btn" @click="exportCSV">
          <text>📤 导出CSV</text>
        </button>
        <button class="action-btn" @click="triggerImportCSV">
          <text>📥 导入CSV</text>
        </button>
      </view>
      <view class="result-info" v-else>
        <text class="info-badge">📊 预报结果</text>
        <text class="info-text">模型: {{ result.modelName }} v{{ result.modelVersion }}</text>
        <text class="info-text">计算时间: {{ result.computeTime }}</text>
      </view>
    </view>

    <!-- 图表视图 -->
    <view class="chart-view" v-if="currentView === 'chart'">
      <ChartRainFlow v-model:data="localData" :startTime="startTime" type="forecast-editer" />
      <view class="chart-hint" :style="{ visibility: currentView !== 'chart' ? 'visible' : 'hidden' }">
        <text>💡 点击图表数据点可以编辑单个值 | 鼠标滚轮缩放 | 拖拽平移视图</text>
      </view>
    </view>

    <!-- 表格视图 -->
    <view class="table-view" v-else>
      <view class="table-controls">
        <text class="table-info">共 {{ localData.length }} 个时段</text>
        <view class="table-filters">
          <text class="filter-label">显示:</text>
          <select v-model="tableFilter" class="filter-select">
            <option value="all">全部</option>
            <option value="day">按天</option>
            <option value="nonzero">非零值</option>
          </select>
        </view>
      </view>
      
      <view class="table-container">
        <view class="table-header" :class="{ 'no-action': result }">
          <text class="table-col col-index">#</text>
          <text class="table-col col-time">时间</text>
          <text class="table-col col-value">降雨量(mm)</text>
          <text class="table-col col-value">径流(m³/s)</text>
          <text class="table-col col-action" v-if="!result">操作</text>
        </view>
        <view class="table-body">
          <view 
            v-for="(item, index) in filteredTableData" 
            :key="index"
            class="table-row"
            :class="{ editing: editingIndex === index, 'no-action': result }"
          >
            <text class="table-col col-index">{{ index + 1 }}</text>
            <text class="table-col col-time">{{ formatTime(item) }}</text>
            <view class="table-col col-value">
              <input 
                v-if="editingIndex === index"
                class="table-input"
                type="number"
                step="0.1"
                v-model.number="item.value"
                @blur="editingIndex = null"
                @keyup.enter="editingIndex = null"
              />
              <text v-else class="value-text">{{ item.value.toFixed(1) }}</text>
            </view>
            <view class="table-col col-value">
              <text class="value-text">{{ (item.value2 || 0).toFixed(1) }}</text>
            </view>
            <view class="table-col col-action" v-if="!result">
              <button 
                class="edit-btn"
                @click="editingIndex = index"
              >
                编辑
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 批量填充弹窗 -->
    <view class="modal-overlay" v-if="showBatchFill" @click="showBatchFill = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">批量填充降雨数据</text>
          <text class="modal-close" @click="showBatchFill = false">✕</text>
        </view>
        
        <view class="modal-body">
          <!-- 当前合计显示 -->
          <view class="current-total">
            <text class="total-label">当前降雨合计:</text>
            <text class="total-value">{{ currentTotalRainfall }} mm</text>
          </view>

          <view class="form-group">
            <text class="form-label">填充方式</text>
            <view class="radio-group">
              <label 
                v-for="mode in fillModes" 
                :key="mode.value"
                class="radio-label"
              >
                <input 
                  type="radio" 
                  :value="mode.value"
                  v-model="batchFillConfig.mode"
                />
                <text>{{ mode.label }}</text>
              </label>
            </view>
            <text class="form-hint">
              {{ batchFillConfig.mode === 'average' ? '将目标合计数平均分配到所有时段' : '按当前各时段降雨比例，调整到目标合计数' }}
            </text>
          </view>

          <view class="form-group">
            <text class="form-label">目标合计数 (mm)</text>
            <input 
              type="number" 
              step="0.1"
              v-model.number="batchFillConfig.targetTotal"
              class="form-input"
              placeholder="输入目标总降雨量"
            />
            <text class="form-hint" v-if="batchFillConfig.mode === 'average' && localData.length > 0">
              平均每时段: {{ (batchFillConfig.targetTotal / localData.length).toFixed(2) }} mm
            </text>
          </view>
        </view>

        <view class="modal-footer">
          <button class="modal-btn modal-btn-cancel" @click="showBatchFill = false">
            取消
          </button>
          <button class="modal-btn modal-btn-confirm" @click="applyBatchFill">
            应用
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import ChartRainFlow from '../charts/ChartRainFlow.vue';

export default {
  name: 'ForecastEditor',
  props: {
    data: {
      type: Array,
      default: () => []
    },
    result: {
      type: Object,
      default: null
    },
    startTime: {
      type: String,
      default: ''
    },
    prdt: {
      type: Number,
      default: 30
    }
  },
  components: { ChartRainFlow },
  emits: ['update:data', 'data-change'],
  setup(props, { emit }) {
    const localData = ref([])
    const currentView = ref('chart')
    const chartContainer = ref(null)
    const chartWidth = ref(800)
    const editingIndex = ref(null)
    const tableFilter = ref('all')
    const showBatchFill = ref(false)

    const viewTabs = [
      { value: 'chart', label: '图表视图', icon: '📊' },
      { value: 'table', label: '表格视图', icon: '📋' }
    ]

    const fillModes = [
      { value: 'average', label: '平均分配' },
      { value: 'proportion', label: '按比例调整' }
    ]

    const batchFillConfig = ref({
      mode: 'average',
      targetTotal: 0
    })

    // 当前降雨总量
    const currentTotalRainfall = computed(() => {
      const total = localData.value.reduce((sum, item) => sum + (item.value || 0), 0)
      return total.toFixed(1)
    })

    // 初始化数据
    const initData = () => {
      // 如果有 result 数据（预报结果），使用 timeSeries
      if (props.result && props.result.timeSeries) {
        localData.value = props.result.timeSeries.map((item, index) => ({
          time: item.time,
          day: Math.floor(index / 8) + 1,
          period: (index % 8) + 1,
          value: item.rain || 0,  // 降雨
          value2: item.QSim || 0,  // 径流
          isWarmUp: item.isWarmUp
        }))
      } else if (props.data && props.data.length > 0) {
        // 从props初始化数据
        localData.value = JSON.parse(JSON.stringify(props.data))
      }
    }

    // 过滤表格数据
    const filteredTableData = computed(() => {
      let data = localData.value
      
      if (tableFilter.value === 'nonzero') {
        data = data.filter(item => item.value > 0)
      } else if (tableFilter.value === 'day') {
        // 只显示每天的第一个时段
        data = data.filter(item => item.period === 1)
      }
      
      // 时间倒序（最新的在最前面）
      return [...data].reverse()
    })

    // 格式化时间
    const formatTime = (item) => {
      const date = new Date(item.time)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:00`
    }

    // 批量填充
    const applyBatchFill = () => {
      const { mode, targetTotal } = batchFillConfig.value
      
      if (!targetTotal || targetTotal < 0) {
        uni.showToast({
          title: '请输入有效的目标合计数',
          icon: 'none'
        })
        return
      }
      
      if (localData.value.length === 0) {
        uni.showToast({
          title: '没有降雨数据',
          icon: 'none'
        })
        return
      }

      if (mode === 'average') {
        // 平均分配：将目标合计数平均分配到所有时段
        const avgValue = targetTotal / localData.value.length
        localData.value.forEach(item => {
          item.value = Math.round(avgValue * 10) / 10
        })
      } else if (mode === 'proportion') {
        // 按比例调整：根据当前各时段的比例调整到目标合计数
        
        // 计算当前总降雨量
        const currentTotal = localData.value.reduce((sum, item) => {
          return sum + (item.value || 0)
        }, 0)
        
        if (currentTotal === 0) {
          uni.showToast({
            title: '当前降雨量为0，无法按比例调整',
            icon: 'none'
          })
          return
        }
        
        // 计算调整比例
        const ratio = targetTotal / currentTotal
        
        // 按比例调整每个时段
        localData.value.forEach(item => {
          const newValue = item.value * ratio
          item.value = Math.round(newValue * 10) / 10
        })
      }

      handleDataChange()
      showBatchFill.value = false
      
      uni.showToast({
        title: `已调整${localData.value.length}个时段`,
        icon: 'success'
      })
    }

    // CSV导出
    const exportCSV = () => {
      let csv = '时间,降雨量(mm),径流(m³/s)\n'
      localData.value.forEach(item => {
        const date = new Date(item.time)
        const timeStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:00`
        csv += `${timeStr},${item.value},${item.value2 || 0}\n`
      })

      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `rainfall_flow_data_${Date.now()}.csv`
      link.click()
      
      // 使用兼容性方式显示提示
      if (typeof uni !== 'undefined' && typeof uni.showToast === 'function') {
        uni.showToast({
          title: '导出成功',
          icon: 'success'
        })
      } else {
        console.log('导出成功')
      }
    }

    // CSV导入
    const triggerImportCSV = () => {
      try {
        // 创建一个临时的input元素来选择文件
        const input = document.createElement('input')
        input.type = 'file'
        input.accept = '.csv'
        input.style.display = 'none'
        
        input.onchange = (event) => {
          const file = event.target.files[0]
          if (!file) return

          const reader = new FileReader()
          reader.onload = (e) => {
            try {
              const text = e.target.result
              const lines = text.split('\n')
              let successCount = 0
              let totalCount = 0
              
              // 跳过表头
              for (let i = 1; i < lines.length; i++) {
                const line = lines[i].trim()
                if (!line) continue
                
                totalCount++
                const parts = line.split(',')
                if (parts.length >= 2) {
                  const timeStr = parts[0].trim()
                  const value = parseFloat(parts[1]) || 0
                  
                  // 解析CSV中的时间
                const csvDate = new Date(timeStr.replace(' ', 'T'))
                
                if (isNaN(csvDate.getTime())) {
                  console.warn('无法解析时间:', timeStr)
                  continue
                }
                
                // 根据时间戳匹配数据项（允许一定误差）
                const matchingIndex = localData.value.findIndex(item => {
                  const itemDate = new Date(item.time)
                  // 时间戳相差在1分钟内视为匹配
                  const timeDiff = Math.abs(csvDate.getTime() - itemDate.getTime())
                  return timeDiff < 60000 // 60秒
                })
                
                if (matchingIndex !== -1) {
                  // 设置降雨数据
                  localData.value[matchingIndex].value = value
                  
                  // 如果CSV中有第三个字段，设置径流数据
                  if (parts.length >= 3) {
                    const flowValue = parseFloat(parts[2]) || 0
                    localData.value[matchingIndex].value2 = flowValue
                  }
                  
                  successCount++
                } else {
                  console.warn('未找到匹配时间:', timeStr)
                }
                }
              }

              handleDataChange()
              
              // 使用兼容性方式显示提示
              if (typeof uni !== 'undefined' && typeof uni.showToast === 'function') {
                uni.showToast({
                  title: `成功导入 ${successCount}/${totalCount} 条数据`,
                  icon: 'success',
                  duration: 2000
                })
              } else {
                console.log(`成功导入 ${successCount}/${totalCount} 条数据`)
              }
            } catch (error) {
              console.error('CSV导入失败:', error)
              // 使用兼容性方式显示错误
              if (typeof uni !== 'undefined' && typeof uni.showToast === 'function') {
                uni.showToast({
                  title: '导入失败: ' + error.message,
                  icon: 'none',
                  duration: 3000
                })
              } else {
                console.error('导入失败:', error.message)
              }
            }
          }
          reader.readAsText(file)
          
          // 清理临时元素
          setTimeout(() => {
            if (input && input.parentNode) {
              input.parentNode.removeChild(input)
            }
          }, 100)
        }
        
        // 添加到DOM并触发点击
        document.body.appendChild(input)
        input.click()
      } catch (error) {
        console.error('触发文件选择失败:', error)
        if (typeof uni !== 'undefined' && typeof uni.showToast === 'function') {
          uni.showToast({
            title: '无法打开文件选择器',
            icon: 'none',
            duration: 2000
          })
        }
      }
    }

    const handleDataChange = () => {
      emit('update:data', JSON.parse(JSON.stringify(localData.value)))
      emit('data-change')
    }

    watch(() => props.data, (newData) => {
      if (newData && newData.length > 0) {
        localData.value = JSON.parse(JSON.stringify(newData))
      }
    }, { deep: true })

    watch(() => props.result, (newResult) => {
      if (newResult && newResult.timeSeries) {
        console.log('收到预报结果数据:', newResult.timeSeries.length, '条')
        initData()
      }
    }, { deep: true, immediate: true })

    onMounted(() => {
      initData()
    })

    return {
      localData,
      currentView,
      viewTabs,
      chartContainer,
      chartWidth,
      editingIndex,
      tableFilter,
      filteredTableData,
      showBatchFill,
      fillModes,
      batchFillConfig,
      currentTotalRainfall,
      formatTime,
      applyBatchFill,
      exportCSV,
      triggerImportCSV
    }
  }
}
</script>

<style scoped>
.rainfall-editor {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.view-tabs {
  display: flex;
  gap: 8px;
}

.view-tab {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.view-tab:hover {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.view-tab.active {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

.tab-icon {
  font-size: 16px;
}

.tab-text {
  font-size: 14px;
  font-weight: 500;
}

.view-tab.active .tab-text {
  color: #fff;
}

.toolbar-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 8px 16px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover {
  border-color: #409eff;
  color: #409eff;
  background-color: #ecf5ff;
}

/* 结果信息 */
.result-info {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  border: 1px solid #91d5ff;
  border-radius: 6px;
}

.info-badge {
  padding: 4px 12px;
  background-color: #1890ff;
  color: #fff;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.info-text {
  font-size: 13px;
  color: #595959;
}

/* 图表视图 */
.chart-view {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.chart-container {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  overflow-x: auto;
}

.chart-canvas {
  width: 100%;
  height: 500px;
}

.chart-hint {
  padding: 12px 16px;
  background-color: #f0f9ff;
  border-left: 3px solid #409eff;
  border-radius: 4px;
  font-size: 13px;
  color: #0c5caf;
}

/* 表格视图 */
.table-view {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.table-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.table-info {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.table-filters {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
}

.filter-select {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  background-color: #fff;
}

.table-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  max-height: 600px;
  overflow-y: auto;
}

.table-header {
  display: grid;
  grid-template-columns: 60px 2fr 1fr 1fr 100px;
  background-color: #f5f7fa;
  border-bottom: 2px solid #e4e7ed;
  font-weight: 600;
  position: sticky;
  top: 0;
  z-index: 10;
}

.table-header.no-action {
  grid-template-columns: 60px 2fr 1fr 1fr;
}

.table-row {
  display: grid;
  grid-template-columns: 60px 2fr 1fr 1fr 100px;
  border-bottom: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.table-row.no-action {
  grid-template-columns: 60px 2fr 1fr 1fr;
}

.table-row:hover {
  background-color: #fafafa;
}

.table-row.editing {
  background-color: #ecf5ff;
}

.table-col {
  padding: 12px 16px;
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
}

.col-index {
  justify-content: center;
  color: #909399;
}

.col-value {
  font-family: 'Monaco', 'Courier New', monospace;
  font-weight: 600;
  color: #409eff;
}

.table-input {
  width: 100%;
  padding: 4px 8px;
  border: 1px solid #409eff;
  border-radius: 4px;
  font-size: 14px;
  font-family: 'Monaco', 'Courier New', monospace;
}

.value-text {
  cursor: pointer;
}

.edit-btn {
  padding: 4px 12px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-width: 500px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.modal-close {
  font-size: 24px;
  color: #909399;
  cursor: pointer;
  line-height: 1;
  transition: color 0.3s;
}

.modal-close:hover {
  color: #606266;
}

.modal-body {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

/* 当前合计显示 */
.current-total {
  padding: 16px;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  border-left: 4px solid #409eff;
  border-radius: 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.total-value {
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
  font-family: 'Monaco', 'Courier New', monospace;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-size: 14px;
  color: #303133;
  font-weight: 600;
}

.form-hint {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
}

.radio-group {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
}

.date-range,
.range-inputs {
  display: flex;
  align-items: center;
  gap: 12px;
}

.date-input,
.form-input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}

.date-input:focus,
.form-input:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #e4e7ed;
  background-color: #fafafa;
}

.modal-btn {
  padding: 10px 24px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.modal-btn-cancel {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.modal-btn-cancel:hover {
  background-color: #f5f7fa;
}

.modal-btn-confirm {
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
  color: #fff;
}

.modal-btn-confirm:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}
</style>

